var websock = null;
let reconnectTimer; //断线重连后，延迟5秒重新创建WebSocket连接  rec用来存储延迟请求的代码
let isConnect = false; //连接标识 避免重复连接
let checkMsg = "heartbeat"; //心跳发送/返回的信息 服务器和客户端收到的信息内容如果如下 就识别为心跳信息 不要做业务处理
// import app from "../../main.js";
// var globalCallback = function () {};
import settings from "@/settings";

// 初始化websocket
function initWebSocket() {
  // ws地址 -->这里是你的请求路径
  // let uName = localStorage.getItem("uName");
  websock = new WebSocket(settings.socketServer());
  websock.onclose = websocketClose;
  websock.onopen = websocketOpen;
  websock.onerror = websocketOnerror;
  websock.onmessage = websocketOnmessage;
}

let createWebSocket = () => {
  try {
    initWebSocket(); //初始化websocket连接
  } catch (e) {
    console.error("尝试创建连接失败", e);
    reConnect(); //如果无法连接上webSocket 那么重新连接！可能会因为服务器重新部署，或者短暂断网等导致无法创建连接
  }
};

//定义重连函数
let reConnect = () => {
  console.log("尝试重新连接");
  if (isConnect) return; //如果已经连上就不在重连了
  reconnectTimer && clearTimeout(reconnectTimer);
  reconnectTimer = setTimeout(function () {
    // 延迟5秒重连  避免过多次过频繁请求重连
    createWebSocket();
  }, 5000);
};
//设置关闭连接
let closeWebSocket = () => {
  webSocket.close();
  isConnect = false;
};
//心跳设置
var heartCheck = {
  timeout: 20000, //每段时间发送一次心跳包 这里设置为20s
  timeoutObj: null, //延时发送消息对象（启动心跳新建这个对象，收到消息后重置对象）
  start: function () {
    this.timeoutObj = setTimeout(function () {
      if (isConnect) websock.send(checkMsg);
    }, this.timeout);
  },
  reset: function () {
    clearTimeout(this.timeoutObj);
    this.start();
  },
  stop: function () {
    clearTimeout(this.timeoutObj);
  },
};

const readySendArray = [];

const addStaySend = function (data, callback) {
  readySendArray.push({ data, callback });
};
// 创建 websocket 连接
function websocketOpen(e) {
  console.log("WebSocket连接成功", e);
  isConnect = true;
  heartCheck.start();
  let send;
  while ((send = readySendArray.pop()) !== undefined) {
    sendData(item.data, item.callback);
  }
}

// 关闭
function websocketClose(e) {
  isConnect = false; //断开后修改标识
  reConnect();
  console.log("WebSocket链接关闭", e);
}

function websocketOnerror() {
  console.log("WebSocket连接发生错误");
  isConnect = false; //连接断开修改标识
  heartCheck.stop();
  reConnect(); //连接错误 需要重连
}

// function getSock(callback) {
//   globalCallback = callback
// }
// 数据接收
function websocketOnmessage(e) {
  if (!e) {
    heartCheck.reset();
    return;
  }
  if (!e.data) {
    //todo
    return;
  }
  let json = null;
  let data = null;
  try {
    // json = JSON.parse(decodeUnicode(e.data))
    json = JSON.parse(e.data);
  } catch (e) {
    data = e.data;
  }
  if (data !== null) {
    return;
  }
  // console.log(json, 'json 字符串')
  if (json === null) {
    return;
  }
  handleArray.forEach((handle) => {
    handle(json);
  });

  // globalCallback(JSON.parse(e.data))
  function decodeUnicode(str) {
    str = str.replace(/\\/g, "%");
    //转换中文
    str = unescape(str);
    //将其他受影响的转换回原来
    str = str.replace(/%/g, "\\");
    //对网址的链接进行处理
    str = str.replace(/\\/g, "");
    return str;
  }
}

// 数据发送
function websocketSend(message) {
  websock.send(message);
}

// 实际调用的方法
function sendData(data, callback) {
  // globalCallback = callback
  // console.log(globalCallback)
  if (typeof data === undefined) {
    return;
  }
  switch (websock.readyState) {
    case websock.OPEN: {
      // 若是ws开启状态
      var message = data;
      if (typeof data === "object") {
        message = JSON.stringify(data);
      } else if (typeof data === "function") {
        message = data();
      }
      websocketSend(message);
      callback && callback();
      break;
    }
    case websock.CONNECTING: {
      // 若是 正在开启状态，则等待1s后重新调用
      setTimeout(function () {
        sendData(data, callback);
      }, 500);
      break;
    }
    case websock.CLOSING: {
    }
    case websock.CLOSED: {
      addStaySend(data, callback);
    }
  }
}

const subscribe = function (topic) {
  if (typeof topic === "string") {
    sendData("subscribe:" + topic);
    return;
  }
  if (topic instanceof Array) {
    sendData("subscribes:" + topic.join(","));
  }
};

const unsubscribe = function (topic) {
  if (typeof topic === "string") {
    sendData("unsubscribe:" + topic);
    return;
  }
  if (topic instanceof Array) {
    sendData("unsubscribes:" + topic.join(","));
  }
};

var handleArray = [];
function addHandle(e) {
  handleArray.push(e);
}
function removeHandle(e) {
  for (var i = 0; i < handleArray.length; i++) {
    if (e === handleArray[i]) {
      handleArray.splice(i, 1);
      break;
    }
  }
}

export default {
  createWebSocket,
  websocketOnmessage,
  sendData,
  closeWebSocket,
  subscribe,
  unsubscribe,
  addHandle,
  removeHandle,
};
